package cn.tangshh.universal.core.util;

import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 线程局部变量工具
 *
 * @author Tang
 * @version v1.0
 * @since 2024/05/30
 */
public final class ThreadLocalUtil {
    private static final ThreadLocal<Map<String, String>> MAP_THREAD_LOCAL = ThreadLocal.withInitial(HashMap::new);

    /**
     * 获取局部变量值
     *
     * @param key key
     * @return {@link String }
     */
    public static String get(String key) {
        Map<String, String> local = MAP_THREAD_LOCAL.get();
        if (CollectionUtils.isEmpty(local)) {
            return null;
        }
        return local.get(key);
    }

    /**
     * 获取局部变量值
     *
     * @param key          key
     * @param defaultValue 默认值
     * @return {@link String }
     */
    public static String get(String key, String defaultValue) {
        String value = get(key);
        if (value == null) {
            return defaultValue;
        }
        return value;
    }


    /**
     * 设置局部变量值
     *
     * @param key   key
     * @param value vale
     * @return {@link String }
     */
    public static String set(String key, String value) {
        Map<String, String> local = MAP_THREAD_LOCAL.get();
        return local.put(key, value);
    }

    /**
     * 设置局部变量值
     *
     * @param map map
     */
    public static void set(Map<String, String> map) {
        Map<String, String> local = MAP_THREAD_LOCAL.get();
        local.putAll(map);
    }

    /**
     * 清除局部变量值
     */
    public static void clear() {
        MAP_THREAD_LOCAL.remove();
    }
}
